#
# Dec 18, 2012
# Cheng-Chun Tu
# parsing topology file in two text, create mininet topology

"""Custom topology example

author: Brandon Heller (brandonh@stanford.edu)

Two directly connected switches plus a host for each switch:

   host --- switch --- switch --- host

Adding the 'topos' dict with a key/value pair to generate our newly defined
topology enables one to pass in '--topo=mytopo' from the command line.
"""
import sys
from mininet.topo import Topo, Node

def parse_topo_file(swfile, edgefile):
	"""
	node file: 1 LosAngeles,CA 
	edge file: 218 44 7 5 4 2 1 47 ;5.27232255516299e-05
	"""
	sw_list = []
	edge_list = []
	swf = open(swfile)
	for line in swf:
		elem = line.split()	
		if elem[0].isdigit():
			sw_list.append(int(elem[0]))
			#print "addnode", elem[0]
	swf.close()

	edgef = open(edgefile)
	for line in edgef:
		elem = line.split()
		if elem[0].isdigit() and elem[1].isdigit():
			edge = (int(elem[0]), int(elem[1]))
			edge_list.append(edge)	
			#print "addedge", elem[1], "--", elem[2]	
	edgef.close()	

	return (list(set(sw_list)), list(set(edge_list)))

class MyTopo( Topo ):
    "Simple topology example."

    def __init__( self, enable_all = True ):

        "Create custom topo."
        
	# Add default members to class.
        super( MyTopo, self ).__init__()
	
	swfile = "MAPPING"
	edgefile = "CONVERTED.POP.1221"
	(sw_list, edge_list) = parse_topo_file(swfile, edgefile)
        
	#print sw_list
	#print edge_list
	# Set Node IDs for hosts and switches

        # Add switches
	for swid in sw_list:
		self.add_node( swid, Node( is_switch=True ) )
	
	# Add node 
	base = len(sw_list)
	for swid in sw_list:
	        self.add_node( swid + base, Node( is_switch=False ) )

        # Add edges between switches
	for edge in edge_list: 
		(sw_left, sw_right) = edge
		print "addedge", sw_left, " -- ", sw_right
		self.add_edge(sw_left, sw_right)
        # Add edges between switch and host
	for swid in sw_list:
		self.add_edge(swid, swid + base)

        # Consider all switches and hosts 'on'
        self.enable_all()


topos = { 'mytopo': ( lambda: MyTopo() ) }
